package com.xx.pmis.web.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.junit.Test;

import com.xx.pmis.model.User;
import com.xx.pmis.services.UserService;
import com.xx.pmis.web.forms.LoginForm;

/**
 * @class 用户登录Action类 <br>
 * 
 * @editor 石星星 @Date 2011-9-21 下午03:13:37 <br>
 * @version jdk_1.5.0
 */
public class LoginAction extends LoginBaseAction {
	private static final Log log = LogFactory.getLog(LoginAction.class);
	UserService userService = getPMISServices().getUserService();
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		//UserService userService = getPMISServices().getUserService();
		ActionErrors errors = new ActionErrors();
		LoginForm f = (LoginForm) form;

		String username = f.getUsername();
		String password = f.getPassword();
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
		}
		session = request.getSession(true);
		boolean isLogin = false;
		String[] us = new String[2];// 定义一个字符串型二维数组
		try {
			us = userService.login(username, password);
		} catch (Exception e) {
			log.info("根据用户名和密码查询该用户异常！" + e.toString());
		}

		User user = new User();

		if (us[0] == null) {
			isLogin = false;
			String error = "登录名或者密码错误！";
			request.setAttribute("error", error);
			return mapping.findForward("fail");
		}
		if (us[0].equals("1")) {
			try {
				user = userService.getUserByUserName(us[1]);
				log.info("****************" + us[1]);
	            log.info("****************" + user.getLoginName());
			} catch (Exception e) {
				log.info("根据用名查询该用户异常！" + e.toString());
			}
			isLogin = true;
		} else {
			isLogin = false;
		}
		String realName = us[1];
		if (isLogin) {
			session.setAttribute("username", username);
			session.setAttribute("isLogin", Boolean.valueOf(true));
			request.getSession().setAttribute("realName", realName);
		    request.getSession().setAttribute("realCode", user.getUserCode());
			session.setAttribute("user", user);
			return mapping.findForward("success");
		}
		errors.add("messages", new ActionMessage(username + "，登录失败"));
		String error = "登录名或者密码错误，请重新输入！";
		request.setAttribute("error", error);
		return mapping.findForward("fail");
	}
	
	@Test
	public void testLogin() {
		try {
			User user = userService.getUserByUserName("sxx");
			System.out.println("" + user.getLoginName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}